package com.jiuhao.conf;//package com.baidu.jiuhao.es.authconf;


import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Configuration
public class ElasticsearchConfig {

    @Value("${elasticsearch.hosts}") // 从配置文件读取ES地址，默认localhost:9200
    private String hosts;

    @Value("${elasticsearch.connectTimeout:5000}") // 连接超时时间（毫秒）
    private int connectTimeout;

    @Value("${elasticsearch.socketTimeout:30000}") // 数据传输超时时间（毫秒）
    private int socketTimeout;

    @Value("${elasticsearch.username}")
    private String username;

    @Value("${elasticsearch.password}")
    private String password;

    @Bean(destroyMethod = "close") // 自动关闭客户端
    public RestHighLevelClient restHighLevelClient() {
        // 解析多节点地址（关键逻辑）
        List<HttpHost> httpHosts = Arrays.stream(hosts.split(","))
                .map(host -> {
                    String[] parts = host.split(":");
                    return new HttpHost(parts[0], Integer.parseInt(parts[1]), "http");  // 协议默认http，https需修改
                })
                .collect(Collectors.toList());


        RestClientBuilder builder = RestClient.builder(httpHosts.toArray(new HttpHost[0]));

        // 配置连接参数
        builder.setRequestConfigCallback(requestConfigBuilder -> {
            requestConfigBuilder.setConnectTimeout(connectTimeout);
            requestConfigBuilder.setSocketTimeout(socketTimeout);
            return requestConfigBuilder;
        });


        // 新增：配置认证信息（仅当用户名密码非空时生效）
        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(username, password));

            builder.setHttpClientConfigCallback(httpClientBuilder -> {
                httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                return httpClientBuilder;
            });
        }

        return new RestHighLevelClient(builder);
    }
}

